// 主游戏启动文件
class Game {
    constructor() {
        this.gameEngine = null;
        this.gameManager = null;
        this.storageManager = null;
        this.isInitialized = false;
    }
    
    async init() {
        try {
            console.log('初始化游戏...');
            window.debugLog && window.debugLog('开始游戏初始化...');
            
            // 等待DOM加载完成
            if (document.readyState === 'loading') {
                window.debugLog && window.debugLog('等待DOM加载完成...');
                await new Promise(resolve => {
                    document.addEventListener('DOMContentLoaded', resolve);
                });
            }
            window.debugLog && window.debugLog('DOM已准备就绪');
            
            // 初始化存储管理器
            window.debugLog && window.debugLog('初始化存储管理器...');
            this.storageManager = new StorageManager();
            window.storageManager = this.storageManager;
            
            // 初始化存档系统
            window.debugLog && window.debugLog('初始化存档系统...');
            this.saveSystem = new SaveSystem();
            window.saveSystem = this.saveSystem;
            
            // 初始化关卡选择系统
            window.debugLog && window.debugLog('初始化关卡选择系统...');
            this.levelSelectMenu = new LevelSelectMenu();
            window.levelSelectMenu = this.levelSelectMenu;
            this.levelSelectMenu.init(this.saveSystem);
            
            // 初始化游戏管理器
            window.debugLog && window.debugLog('初始化游戏管理器...');
            this.gameManager = new GameManager();
            window.gameManager = this.gameManager;
            
            // 初始化游戏引擎
            window.debugLog && window.debugLog('初始化游戏引擎...');
            this.gameEngine = new GameEngine();
            window.gameEngine = this.gameEngine;
            
            // 设置事件监听器
            this.setupEventListeners();
            
            // 检查是否有存档
            this.checkSaveGame();
            
            // 初始化新技能树系统
            window.debugLog && window.debugLog('初始化新技能树系统...');
            try {
                if (typeof NewSkillTreeSystem !== 'undefined') {
                    window.newSkillTree = new NewSkillTreeSystem();
                    window.newSkillTreeSystem = window.newSkillTree; // 别名兼容
                    window.debugLog && window.debugLog('✓ 新技能树系统初始化成功');
                } else {
                    window.debugLog && window.debugLog('✗ NewSkillTreeSystem 类不可用');
                }
            } catch (skillTreeError) {
                console.error('新技能树系统初始化失败:', skillTreeError);
                window.debugLog && window.debugLog('✗ 新技能树系统初始化失败: ' + skillTreeError.message);
            }
            
            // 保持旧系统兼容性
            try {
                if (typeof WeaponEnhancementSystem !== 'undefined') {
                    window.weaponEnhancement = new WeaponEnhancementSystem();
                }
            } catch (weaponEnhancementError) {
                console.warn('旧武器强化系统初始化失败:', weaponEnhancementError);
            }
            
            // 启动游戏循环
            this.gameEngine.start();
            
            // 最后初始化成就系统
            window.debugLog && window.debugLog('最后初始化成就系统...');
            window.debugLog && window.debugLog('检查AchievementSystem: ' + typeof AchievementSystem);
            try {
                if (typeof AchievementSystem !== 'undefined') {
                    window.achievementSystem = new AchievementSystem();
                    window.achievementSystem.init();
                    window.debugLog && window.debugLog('✓ 成就系统初始化成功');
                } else {
                    window.debugLog && window.debugLog('✗ AchievementSystem 类不可用');
                }
            } catch (achievementError) {
                console.error('成就系统初始化失败:', achievementError);
                window.debugLog && window.debugLog('✗ 成就系统初始化失败: ' + achievementError.message);
            }
            
            this.isInitialized = true;
            console.log('游戏初始化完成！');
            window.debugLog && window.debugLog('✅ 游戏初始化完成！');
            
        } catch (error) {
            console.error('游戏初始化失败:', error);
            console.error('错误堆栈:', error.stack);
            
            // 显示具体错误信息以便调试
            const errorMsg = `游戏初始化失败: ${error.message}`;
            if (this.showError) {
                this.showError(errorMsg);
            } else {
                alert(errorMsg + '\n请检查浏览器控制台获取详细信息');
            }
        }
    }
    
    setupEventListeners() {
        // 开始游戏按钮
        const startButton = document.getElementById('startButton');
        if (startButton) {
            startButton.addEventListener('click', () => {
                this.startNewGame();
            });
        }
        
        // 继续游戏按钮
        const loadButton = document.getElementById('loadButton');
        if (loadButton) {
            loadButton.addEventListener('click', () => {
                this.continueGame();
            });
        }
        
        // 重新开始按钮
        const restartButton = document.getElementById('restartButton');
        if (restartButton) {
            restartButton.addEventListener('click', () => {
                this.restartGame();
            });
        }
        
        // 返回主菜单按钮
        const mainMenuButton = document.getElementById('mainMenuButton');
        if (mainMenuButton) {
            mainMenuButton.addEventListener('click', () => {
                this.returnToMenu();
            });
        }
        
        const menuButton = document.getElementById('menuButton');
        if (menuButton) {
            menuButton.addEventListener('click', () => {
                this.returnToMenu();
            });
        }
        
        // 下一关按钮
        const nextLevelButton = document.getElementById('nextLevelButton');
        if (nextLevelButton) {
            nextLevelButton.addEventListener('click', () => {
                this.nextLevel();
            });
        }
        
        // 关卡选择按钮
        const levelSelectButton = document.getElementById('levelSelectButton');
        if (levelSelectButton) {
            levelSelectButton.addEventListener('click', () => {
                this.openLevelSelect();
            });
        }
        
        // 存档管理按钮
        const saveManageButton = document.getElementById('saveManageButton');
        if (saveManageButton) {
            saveManageButton.addEventListener('click', () => {
                this.openSaveManage();
            });
        }
        
        // 成就系统按钮
        const achievementsButton = document.getElementById('achievementsButton');
        if (achievementsButton) {
            achievementsButton.addEventListener('click', () => {
                this.openAchievements();
            });
        }
        
        // 永久升级商店按钮
        const upgradeStoreButton = document.getElementById('upgradeStoreButton');
        if (upgradeStoreButton) {
            upgradeStoreButton.addEventListener('click', () => {
                this.openUpgradeStore();
            });
        }
        
        // 技能树按钮
        const skillTreeButton = document.getElementById('skillTreeButton');
        if (skillTreeButton) {
            skillTreeButton.addEventListener('click', () => {
                this.openSkillTree();
            });
        }
        
        // 移除技能树按钮的事件委托 - 由 weaponEnhancement.js 单独处理
        console.log('技能树按钮事件将由 weaponEnhancement.js 处理');
        
        // 存档管理子按钮
        const quickSaveBtn = document.getElementById('quickSaveBtn');
        if (quickSaveBtn) {
            quickSaveBtn.addEventListener('click', () => {
                this.quickSave();
            });
        }
        
        const quickLoadBtn = document.getElementById('quickLoadBtn');
        if (quickLoadBtn) {
            quickLoadBtn.addEventListener('click', () => {
                this.quickLoad();
            });
        }
        
        const exportSaveBtn = document.getElementById('exportSaveBtn');
        if (exportSaveBtn) {
            exportSaveBtn.addEventListener('click', () => {
                this.exportSave();
            });
        }
        
        const importSaveBtn = document.getElementById('importSaveBtn');
        if (importSaveBtn) {
            importSaveBtn.addEventListener('click', () => {
                document.getElementById('importSaveInput').click();
            });
        }
        
        const importSaveInput = document.getElementById('importSaveInput');
        if (importSaveInput) {
            importSaveInput.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    this.importSave(file);
                }
            });
        }
        
        const saveManageBack = document.getElementById('saveManageBack');
        if (saveManageBack) {
            saveManageBack.addEventListener('click', () => {
                this.returnToMenu();
            });
        }
        
        // 成就系统返回按钮
        const achievementsBack = document.getElementById('achievementsBack');
        if (achievementsBack) {
            achievementsBack.addEventListener('click', () => {
                this.returnToMenu();
            });
        }
        
        // 永久升级商店返回按钮
        const upgradeStoreBack = document.getElementById('upgradeStoreBack');
        if (upgradeStoreBack) {
            upgradeStoreBack.addEventListener('click', () => {
                this.returnToMenu();
            });
        }
        
        // 保存游戏按钮
        const saveGameButton = document.getElementById('saveGameButton');
        if (saveGameButton) {
            saveGameButton.addEventListener('click', () => {
                this.saveCurrentGame();
            });
        }
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            switch (e.code) {
                case 'Escape':
                    if (this.gameEngine.gameState === 'playing') {
                        this.pauseGame();
                    } else if (this.gameEngine.gameState === 'paused') {
                        this.resumeGame();
                    }
                    break;
                    
                case 'KeyR':
                    if (this.gameEngine.gameState === 'gameOver') {
                        this.restartGame();
                    }
                    break;
            }
        });
        
        // 窗口焦点事件
        window.addEventListener('blur', () => {
            if (this.gameEngine && this.gameEngine.gameState === 'playing') {
                this.pauseGame();
            }
        });
        
        // 防止页面滚动
        document.addEventListener('keydown', (e) => {
            if (['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.code)) {
                e.preventDefault();
            }
        });
    }
    
    // 移除 bindSkillTreeButtons 方法 - 由 weaponEnhancement.js 统一处理所有技能树事件
    
    checkSaveGame() {
        const progress = this.gameManager.levelManager.loadProgress();
        const loadButton = document.getElementById('loadButton');
        
        if (loadButton) {
            if (progress && progress.currentLevel > 1) {
                loadButton.style.display = 'inline-block';
                loadButton.textContent = `继续游戏 (第${progress.currentLevel}关)`;
            } else {
                loadButton.style.display = 'none';
            }
        }
    }
    
    startNewGame() {
        console.log('开始新游戏');
        window.debugLog && window.debugLog('点击开始游戏按钮');
        
        try {
            window.debugLog && window.debugLog('隐藏菜单...');
            this.hideAllMenus();
            
            window.debugLog && window.debugLog('调用gameManager.startNewGame...');
            this.gameManager.startNewGame();
            
            // 应用技能效果到玩家和武器
            window.debugLog && window.debugLog('应用技能树效果...');
            setTimeout(() => {
                this.applySkillEffectsAfterGameStart();
            }, 100); // 短暂延迟确保玩家对象已创建
            
            window.debugLog && window.debugLog('记录游戏开始统计...');
            // 记录游戏开始
            try {
                if (this.storageManager) {
                    this.storageManager.updateStatistics('gameStarted');
                    window.debugLog && window.debugLog('游戏开始统计记录成功');
                } else {
                    window.debugLog && window.debugLog('警告: storageManager不可用');
                }
            } catch (statsError) {
                console.error('记录游戏开始统计失败:', statsError);
                window.debugLog && window.debugLog('记录统计失败: ' + statsError.message);
                // 不要让统计错误影响游戏运行
            }
            
            // 检查成就（游戏开始时）
            try {
                if (window.achievementSystem) {
                    window.achievementSystem.checkAchievements();
                    window.debugLog && window.debugLog('成就检查完成');
                }
            } catch (achievementError) {
                console.error('成就检查失败:', achievementError);
                window.debugLog && window.debugLog('成就检查失败: ' + achievementError.message);
            }
            
            window.debugLog && window.debugLog('✓ 游戏启动成功');
        } catch (error) {
            console.error('启动游戏失败:', error);
            window.debugLog && window.debugLog('✗ 游戏启动失败: ' + error.message);
            throw error;
        }
    }
    
    continueGame() {
        console.log('继续游戏');
        this.hideAllMenus();
        this.gameManager.continueGame();
        
        // 继续游戏时也应用技能效果
        setTimeout(() => {
            this.applySkillEffectsAfterGameStart();
        }, 100);
    }
    
    // 游戏开始后应用技能效果
    applySkillEffectsAfterGameStart() {
        try {
            window.debugLog && window.debugLog('🎯 开始应用技能树效果...');
            
            // 确保技能树系统存在并应用效果
            if (window.newSkillTree && typeof window.newSkillTree.applySkillEffects === 'function') {
                window.newSkillTree.applySkillEffects();
                
                // 启动技能效果循环（用于生命恢复等持续效果）
                if (typeof window.newSkillTree.startSkillEffectLoop === 'function') {
                    window.newSkillTree.startSkillEffectLoop();
                }
                
                window.debugLog && window.debugLog('✅ 新技能树效果应用成功');
            } else if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.applySkillEffects === 'function') {
                window.newSkillTreeSystem.applySkillEffects();
                
                // 启动技能效果循环
                if (typeof window.newSkillTreeSystem.startSkillEffectLoop === 'function') {
                    window.newSkillTreeSystem.startSkillEffectLoop();
                }
                
                window.debugLog && window.debugLog('✅ 技能树系统效果应用成功');
            } else {
                window.debugLog && window.debugLog('⚠️ 技能树系统不可用');
            }
            
            // 确保永久升级效果也被应用
            if (window.roguelikeSystem && typeof window.roguelikeSystem.applyPermanentUpgrades === 'function') {
                window.roguelikeSystem.applyPermanentUpgrades();
                window.debugLog && window.debugLog('✅ 永久升级效果应用成功');
            }
            
            // 更新UI
            if (window.gameEngine && typeof window.gameEngine.updateUI === 'function') {
                window.gameEngine.updateUI();
            }
            
            console.log('🎮 游戏开始时技能效果应用完成，持续效果已启动');
            
        } catch (error) {
            console.error('❌ 应用技能效果失败:', error);
            window.debugLog && window.debugLog('技能效果应用失败: ' + error.message);
        }
    }
    
    restartGame() {
        console.log('重新开始游戏');
        this.hideAllMenus();
        this.gameEngine.resetGame();
        this.startNewGame();
    }
    
    returnToMenu() {
        console.log('返回主菜单');
        this.hideAllMenus();
        this.gameEngine.resetGame();
        this.showMenu('startMenu');
        this.checkSaveGame();
    }
    
    nextLevel() {
        console.log('进入下一关');
        this.hideAllMenus();
        
        // 确保游戏状态正确
        if (this.gameEngine) {
            this.gameEngine.gameState = 'playing';
        }
        
        if (!this.gameManager.nextLevel()) {
            // 游戏完成
            this.showGameComplete();
        } else {
            console.log('成功进入第', this.gameManager.levelManager.currentLevel, '关');
        }
    }
    
    pauseGame() {
        if (this.gameManager) {
            this.gameManager.pauseGame();
            
            // 暂停时停止生命恢复循环
            if (window.newSkillTree && typeof window.newSkillTree.stopSkillEffectLoop === 'function') {
                window.newSkillTree.stopSkillEffectLoop();
            } else if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.stopSkillEffectLoop === 'function') {
                window.newSkillTreeSystem.stopSkillEffectLoop();
            }
            
            this.showPauseMenu();
        }
    }
    
    resumeGame() {
        if (this.gameManager) {
            this.gameManager.resumeGame();
            
            // 恢复时重新启动生命恢复循环
            if (window.newSkillTree && typeof window.newSkillTree.startSkillEffectLoop === 'function') {
                window.newSkillTree.startSkillEffectLoop();
            } else if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.startSkillEffectLoop === 'function') {
                window.newSkillTreeSystem.startSkillEffectLoop();
            }
            
            this.hidePauseMenu();
        }
    }
    
    showGameComplete() {
        const totalScore = this.gameManager.score;
        const message = `
            🎉 恭喜完成游戏！ 🎉
            
            最终分数: ${totalScore}
            击杀数: ${this.storageManager.loadData().player.totalKills}
            游戏时间: ${this.formatTime(Date.now() - this.gameManager.gameStartTime)}
            
            你已经成功清理了整个学校的僵尸！
            现在可以自由选择关卡挑战了！
        `;
        
        alert(message);
        
        // 保存完成记录
        this.storageManager.saveScore(totalScore, 0, 10);
        this.storageManager.saveProgress({ level: 10, completed: true });
        
        // 解锁所有关卡
        for (let i = 1; i <= 10; i++) {
            if (!this.saveSystem.getCompletedLevels().includes(i)) {
                this.storageManager.saveProgress({ level: i, completed: true });
            }
        }
        
        this.returnToMenu();
    }
    
    openLevelSelect() {
        if (this.levelSelectMenu) {
            this.levelSelectMenu.openLevelSelect();
        }
    }
    
    openSaveManage() {
        this.hideAllMenus();
        this.showMenu('saveManageMenu');
        this.updateSaveManageUI();
    }
    
    openAchievements() {
        if (window.achievementSystem) {
            // 直接调用成就系统的openAchievements方法
            window.achievementSystem.openAchievements();
        } else {
            // 如果成就系统不可用，回退到基本显示
            this.hideAllMenus();
            this.showMenu('achievementsMenu');
        }
    }
    
    openUpgradeStore() {
        this.hideAllMenus();
        this.showMenu('upgradeStoreMenu');
        if (window.roguelikeSystem) {
            window.roguelikeSystem.updateStoreUI();
        }
    }
    
    openSkillTree() {
        console.log('🌳 打开技能树');
        this.hideAllMenus();
        
        // 优先使用新技能树系统
        if (window.newSkillTree) {
            console.log('使用新技能树系统');
            window.newSkillTree.openSkillTree();
        } else if (window.weaponEnhancement) {
            console.log('使用旧技能树系统');
            window.weaponEnhancement.openSkillTree();
        } else {
            console.error('⚠️ 没有可用的技能树系统');
        }
    }
    
    saveCurrentGame() {
        if (this.saveSystem) {
            this.saveSystem.saveGame('main');
            // 关闭关卡完成菜单并返回主菜单
            this.hideAllMenus();
            this.showMenu('startMenu');
            this.checkSaveGame();
        }
    }
    
    updateSaveManageUI() {
        // 实现存档管理界面的更新
        const saveSlots = document.getElementById('saveSlots');
        if (saveSlots && this.saveSystem) {
            const saveList = this.saveSystem.getSaveList();
            saveSlots.innerHTML = '';
            
            ['main', 'slot1', 'slot2', 'slot3', 'quick'].forEach(slot => {
                const saveInfo = saveList[slot];
                const slotDiv = document.createElement('div');
                slotDiv.className = 'save-slot';
                slotDiv.innerHTML = `
                    <h4>存档槽 ${slot === 'quick' ? '(快速)' : slot === 'main' ? '(主)' : slot}</h4>
                    ${saveInfo ? `
                        <p>${saveInfo.description}</p>
                        <button onclick="window.game.loadSave('${slot}')">加载</button>
                        <button onclick="window.game.deleteSave('${slot}')">删除</button>
                    ` : `
                        <p>空存档</p>
                        <button onclick="window.game.saveToSlot('${slot}')">保存到此槽</button>
                    `}
                `;
                saveSlots.appendChild(slotDiv);
            });
        }
    }
    
    loadSave(slot) {
        if (this.saveSystem) {
            const saveData = this.saveSystem.loadGame(slot);
            if (saveData && this.saveSystem.applySaveData(saveData)) {
                this.hideAllMenus();
                if (window.gameEngine) {
                    window.gameEngine.gameState = 'playing';
                }
            }
        }
    }
    
    deleteSave(slot) {
        if (this.saveSystem && confirm(`确定删除存档 ${slot} 吗？`)) {
            this.saveSystem.deleteSave(slot);
            this.updateSaveManageUI();
        }
    }
    
    saveToSlot(slot) {
        if (this.saveSystem) {
            this.saveSystem.saveGame(slot);
            this.updateSaveManageUI();
        }
    }
    
    quickSave() {
        if (this.saveSystem) {
            this.saveSystem.quickSave();
        }
    }
    
    quickLoad() {
        if (this.saveSystem) {
            const saveData = this.saveSystem.loadGame('quick');
            if (saveData && this.saveSystem.applySaveData(saveData)) {
                this.hideAllMenus();
                if (window.gameEngine) {
                    window.gameEngine.gameState = 'playing';
                }
            } else {
                this.saveSystem.showSaveNotification('没有找到快速存档', true);
            }
        }
    }
    
    exportSave() {
        if (this.saveSystem) {
            this.saveSystem.exportSave('main');
        }
    }
    
    importSave(file) {
        if (this.saveSystem) {
            this.saveSystem.importSave(file, 'main');
            // 延迟更新UI，让导入操作完成
            setTimeout(() => {
                this.updateSaveManageUI();
            }, 500);
        }
    }
    
    showPauseMenu() {
        // 创建暂停菜单（如果不存在）
        let pauseMenu = document.getElementById('pauseMenu');
        if (!pauseMenu) {
            pauseMenu = document.createElement('div');
            pauseMenu.id = 'pauseMenu';
            pauseMenu.className = 'menu';
            pauseMenu.innerHTML = `
                <h2>游戏暂停</h2>
                <button id="resumeButton" class="menu-btn">继续游戏</button>
                <button id="pauseMenuButton" class="menu-btn">返回主菜单</button>
            `;
            document.getElementById('gameContainer').appendChild(pauseMenu);
            
            // 添加事件监听器
            document.getElementById('resumeButton').addEventListener('click', () => {
                this.resumeGame();
            });
            
            document.getElementById('pauseMenuButton').addEventListener('click', () => {
                this.returnToMenu();
            });
        }
        
        pauseMenu.classList.remove('hidden');
    }
    
    hidePauseMenu() {
        const pauseMenu = document.getElementById('pauseMenu');
        if (pauseMenu) {
            pauseMenu.classList.add('hidden');
        }
    }
    
    hideAllMenus() {
        const menus = ['startMenu', 'gameOverMenu', 'levelCompleteMenu', 'pauseMenu', 'saveManageMenu', 'levelSelectMenu', 'achievementsMenu', 'upgradeStoreMenu', 'skillTreeMenu'];
        console.log('🙈 隐藏所有菜单:', menus);
        
        menus.forEach(menuId => {
            const menu = document.getElementById(menuId);
            if (menu) {
                menu.classList.add('hidden');
                console.log(`✅ 已隐藏: ${menuId}`);
            } else {
                console.warn(`⚠️ 找不到菜单: ${menuId}`);
            }
        });
    }
    
    showMenu(menuId) {
        const menu = document.getElementById(menuId);
        if (menu) {
            menu.classList.remove('hidden');
        }
    }
    
    formatTime(milliseconds) {
        const seconds = Math.floor(milliseconds / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        
        if (hours > 0) {
            return `${hours}小时${minutes % 60}分钟`;
        } else if (minutes > 0) {
            return `${minutes}分钟${seconds % 60}秒`;
        } else {
            return `${seconds}秒`;
        }
    }
    
    showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #ff4444;
            color: white;
            padding: 20px;
            border-radius: 10px;
            z-index: 10000;
            text-align: center;
            font-family: monospace;
        `;
        errorDiv.textContent = message;
        
        document.body.appendChild(errorDiv);
        
        setTimeout(() => {
            document.body.removeChild(errorDiv);
        }, 5000);
    }
    
    // 调试方法
    debug() {
        if (this.isInitialized) {
            console.log('Game Debug Info:');
            console.log('- Game Engine:', this.gameEngine);
            console.log('- Game Manager:', this.gameManager);
            console.log('- Storage Manager:', this.storageManager);
            console.log('- Game State:', this.gameEngine.gameState);
            console.log('- Current Level:', this.gameManager.levelManager.currentLevel);
            console.log('- Player:', window.player);
            console.log('- Zombies:', this.gameEngine.zombies.length);
        } else {
            console.log('Game not initialized yet');
        }
    }
}

// 添加成就动画CSS
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOut {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
    
    .achievement-content h3 {
        margin: 0 0 5px 0;
        font-size: 14px;
    }
    
    .achievement-content h4 {
        margin: 0 0 5px 0;
        font-size: 16px;
        font-weight: bold;
    }
    
    .achievement-content p {
        margin: 0;
        font-size: 12px;
        opacity: 0.8;
    }
`;
document.head.appendChild(style);

// 全局游戏实例
window.game = new Game();

// 页面加载完成后初始化游戏
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.game.init();
    });
} else {
    window.game.init();
}

// 调试快捷键
document.addEventListener('keydown', (e) => {
    if (e.ctrlKey && e.shiftKey && e.code === 'KeyD') {
        window.game.debug();
    }
});

// 错误处理
window.addEventListener('error', (e) => {
    console.error('游戏运行错误:', e.error);
    console.error('错误详情:', e.filename, e.lineno, e.colno);
    
    if (window.game && window.game.gameEngine) {
        window.game.gameEngine.gameState = 'error';
    }
    
    // 显示错误信息
    if (window.game && window.game.showError) {
        window.game.showError('游戏出现错误，请按F5刷新页面');
    } else {
        // 如果game对象还未初始化，直接显示错误
        alert('游戏初始化失败，请刷新页面重试');
    }
});

// 防止页面意外关闭时丢失进度
window.addEventListener('beforeunload', (e) => {
    if (window.gameManager && window.gameManager.levelManager.isLevelActive) {
        e.preventDefault();
        e.returnValue = '游戏正在进行中，确定要离开吗？';
    }
});